import {useState, useEffect} from 'react'
import { Table, Space, Button, message } from 'antd';
import {getServiceListRequest} from './ajax'
import {ServiceSchema, ServiceTopicSchema} from '@components/schema/service'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import {getColumns} from './util'
import { CaseSchema } from '@src/components/schema/caseSchema'
import style from './index.module.less'
import {PlusOutlined} from '@ant-design/icons'
import refresh from '@imgs/refresh.png'
import { createFile } from './ajax'
import { Dispatch } from 'redux';
import { useDispatch } from 'react-redux';
import { addWindow } from '@src/redux/actions/tab';

async function initList (id: string, setList: (v: ServiceSchema[]) => void, setLoading: (v: boolean) => void) {
  setLoading(true)
  const [e, d] = await awaitWrap(getServiceListRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setList(d)
  }
}

async function createIdentity (id: string, name: string, caseDetail: CaseSchema, dispatch: Dispatch) {
  const h = message.loading('生成中', 120)
  const caseid = caseDetail.id
  const [e, d] = await awaitWrap(createFile(id, caseid))
  h()
  if (e === null && d !== null) {
    dispatch(addWindow({
      componentName: "PdfReader",
      id: `${caseDetail.id}-${name}`,
      meta: {caseid, fileid: d, readonly: false},
      title: `${caseDetail.caseno_desc}-${name}-送达证明`
    }))
  }
}

interface Props {
  id: string
  caseid: string
  editable: boolean
  topic: ServiceTopicSchema
  caseDetail: CaseSchema
  refreshFn: () => void
  setRefreshListFn: (v: () => void) => void
  showDetail: (d: ServiceSchema) => void
  showResult: (d: ServiceSchema) => void
  showFeedback: (d: ServiceSchema) => void
  showModify: (d: ServiceSchema | null) => void
  showTopicModal: () => void
}

function Main ({id, topic, caseDetail, editable, caseid, refreshFn, showDetail, showResult, showFeedback, setRefreshListFn, showModify, showTopicModal}: Props) {
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<ServiceSchema[]>([])
  const columns = getColumns(topic, caseDetail, editable, showModify, showDetail, showResult, showFeedback, setRefreshListFn, () => initList(id, setList, setLoading), (i, name) => createIdentity(i, name, caseDetail, dispatch))
  useEffect(() => {
    initList(id, setList, setLoading)
  }, [])
  return (
    <div>
      {editable && !topic.complete_datetime ? (
        <div className={style['btn-line']}>
          <Space size='middle'>
            <Button icon={<PlusOutlined />} onClick={() => {
              setRefreshListFn(() => initList(id, setList, setLoading))
              showModify(null)
            }}>添加送达</Button>
            <Button type='primary' onClick={() => {
              const hasSend = list.some(li => ['视为送达', '送达'].indexOf(li.status) !== -1)
              if (!hasSend) {
                return message.warning('确认整体送达情况前，至少要有一条送达情况为“送达”或“视为送达”')
              }
              showTopicModal()
            }}>整体送达情况</Button>
            <a className={style.refresh}><img src={refresh} className={style['refresh-icon']} onClick={() => {
              initList(id, setList, setLoading)
            }} /></a>
          </Space>
        </div>
      ) : (
        <div className={style['total-btn-line']}>
          <div className={style['total-message']}>
            <span>{topic.complete_type}</span>
            <span>{formatDate(topic.complete_datetime)}</span>
            <span>备注：{topic.complete_info || '无'}</span>
          </div>
          {/* <Button className={style.print}>批量打印</Button> */}
        </div>
      )}
      <Table rowKey='order' loading={loading} dataSource={list} pagination={false} columns={columns} />
    </div>
  )
}

export default Main
